﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OreSystem.Entities;
using NHibernate;
namespace OreSystem.DAL
{
    public class ItemDAL
    {      

        public IList<Item> GetList()
        {
            using (ISession session = DaoFactory.CreateSessionFactory().OpenSession())
            {
                return session.CreateQuery("from Item").List<Item>();
            }
        }

        public IList<Item> GetItemByType(int t)
        {
            using (ISession session = DaoFactory.CreateSessionFactory().OpenSession())
            {
                return session.CreateQuery("from Item i where i.Type=:type").SetInt32("type", t).List<Item>();
            }
        }

        public void Save(Item item) {
            using (ISession session = DaoFactory.CreateSessionFactory().OpenSession())
            {
                session.SaveOrUpdate(item);
                session.Flush();
            }
        }
        public void Delete(Item item)
        {
            using (ISession session = DaoFactory.CreateSessionFactory().OpenSession())
            {
                session.Delete(item);
                session.Flush();
            }
        }

        public IList<Item> GetItemsByKeys(int type, string keys, DateTime date) {
            using (ISession session = DaoFactory.CreateSessionFactory().OpenSession()) {
                return session.CreateQuery("from Item i where i.Type=:type and i.CarNumber like:keys").SetInt32("type", type).SetString("keys", "%" + keys + "%").List<Item>();
            }
        }

        public Item GetItemById(int id) {
            using (ISession session = DaoFactory.CreateSessionFactory().OpenSession()) {
                return session.CreateQuery("from Item i where id.ID =:id").SetInt32("id",id).List<Item>().First();
            }
        }

        public void Deletes(IList<object> idList)
        {
            using (ISession session = DaoFactory.CreateSessionFactory().OpenSession())
            {
                foreach (var item in idList)
                {
                    Item entity = session.Get<Item>(item);
                    if (entity != null)
                    {
                        session.Delete(entity);
                    }
                }
                session.Flush();
            }
        }

        public IList<Item> GetItemByCarId(int cid,int type)
        {
            using (ISession session = DaoFactory.CreateSessionFactory().OpenSession())
            {
                return session.CreateQuery("from Item i where i.Type=:type and i.CarID=:cid").SetInt32("type",type).SetInt32("cid",cid).List<Item>();
            }
        }
    }
}
